package auntie.production.app2;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import auntie.production.app2.db.auntie_production_app_db.production_details;
import auntie.production.app2.db.auntie_production_app_db.productions;
import auntie.production.app2.net.mysql_bakery;
import auntie.production.app2.svc.s1;

public class Main extends s1 {

	private static final String LOG = Main.class.getName();

	EditText et_inputer;
	Button btn_go;
	ListView lv_productions;
	LvAdp_Productions lvadp_productions;
	AlertDialog alert_dialog;
	ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		et_inputer = (EditText) findViewById(R.id.et_inputer);
		btn_go = (Button) findViewById(R.id.btn_go);
		lv_productions = (ListView) findViewById(R.id.lv_productions);
		lvadp_productions = new LvAdp_Productions(this);

		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("submitting...");

		btn_go.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				on_go();
				// svc_test_production_details();
			}
		});
		lv_productions.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adp, View vw, int pos,
					long arg3) {
				on_sel_productions(adp, vw, pos);
			}
		});

		lv_productions
				.setOnItemLongClickListener(new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> av, View vw,
							int pos, long arg3) {
						hlp_submit_dialog_show("Submit", av, pos);
						return true;
					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		hlp_productions_adapter();

	}

	@Override
	public void onBackPressed() {
		// do nothing
	}

	// menu listener
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(getApplication()).inflate(R.menu.main_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	private void hlp_submit_dialog_show(String message,
			final AdapterView<?> av, final int pos) {
		AlertDialog.Builder alert_dialog_builder = new AlertDialog.Builder(this);
		alert_dialog_builder.setMessage(message).setCancelable(false)
				.setPositiveButton("Submit",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								submit(av, pos);
							}
						}).setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});

		alert_dialog = alert_dialog_builder.create();
		alert_dialog.show();
	}

	private void hlp_submitall_dialog_show(String message) {
		AlertDialog.Builder alert_dialog_builder = new AlertDialog.Builder(this);
		alert_dialog_builder.setMessage(message).setCancelable(false)
				.setPositiveButton("Submit",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								submit_all();
							}
						}).setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});

		alert_dialog = alert_dialog_builder.create();
		alert_dialog.show();
	}

	void submit(AdapterView<?> av, int pos) {
		productions p = (productions) av.getItemAtPosition(pos);
		SubmitTask ct = new SubmitTask();
		ct.execute(p);
	}

	void submit_all() {
		Log.i(LOG, "submit all");
		SubmitAllTask ct = new SubmitAllTask();
		ct.execute();
	}

	private void sendSMS(String phoneNumber, String message) {
		PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
				Main.class), 0);
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, pi, null);
	}

	private class SubmitTask extends AsyncTask<productions, Void, String> {

		@Override
		protected void onPreExecute() {
			progressDialog.show();
		}

		@SuppressWarnings("finally")
		@Override
		protected String doInBackground(productions... prds) {

			try {

				List<production_details> pds = svc_all_production_details_by_production(prds[0]
						.getId());
				mysql_bakery.mysql_insert_production_details(pds);

				List<productions> ps = new ArrayList<productions>();
				prds[0].setSubmitted(true);
				ps.add(prds[0]);
				mysql_bakery.mysql_insert_productions(ps);

				svc_update_productions(prds[0]);
				String fmsg = "{0,date,E F'w of' MMM} \n TP: {1,number,#,###.##}";
				String sms = MessageFormat.format(fmsg, new Date(), prds[0]
						.getTotal_amount());
				return sms;
			} catch (Exception e) {
				// Toast.makeText(Main.this, "Error Connection", 2000).show();
				return "error";
			}

		}

		@Override
		protected void onPostExecute(String sms) {
			sendSMS("09196358476", sms); // send to anti phone
			sendSMS("09228345773", sms); // send to me
			Log.i(LOG, "sms: " + sms);
			hlp_productions_adapter();
			progressDialog.dismiss();

		}

	}

	private class SubmitAllTask extends AsyncTask<Void, Void, List<String>> {

		@Override
		protected void onPreExecute() {
			progressDialog.show();
		}

		@SuppressWarnings("finally")
		@Override
		protected List<String> doInBackground(Void... params) {

			try {
				List<productions> ps = svc_all_productions();
				for (productions p : ps) {
					p.setSubmitted(true);
					List<production_details> pds = svc_all_production_details_by_production(p
							.getId());

					mysql_bakery.mysql_insert_production_details(pds);
				}

				// List<productions> hps = new ArrayList<productions>();
				// hps.addAll(ps);
				mysql_bakery.mysql_insert_productions(ps);

				String fmsg_h = "{0,date,E F'w of' MMM}";
				StringBuilder sb = new StringBuilder();
				sb.append(MessageFormat.format(fmsg_h, new Date()));

				for (productions p : ps) {
					sb.append("\n");
					String fmsg = "TP: {0,number,#,###.##}";
					sb.append(MessageFormat.format(fmsg, p.getTotal_amount()));
					svc_update_productions(p);
				}

				String msg = sb.toString();
				Log.i(LOG, "msg: " + msg);
				int len = msg.length();
				int cap = 160;
				int nmsg = (int) Math.ceil(((double) len) / cap);
				Log.i(LOG, "nmsg: " + nmsg);

				List<String> msgs = new ArrayList<String>();
				for (int i = 0; i < nmsg; i++) {
					int pv = (i * cap);
					int nx = ((i + 1) * cap);
					if (nx >= len) {
						msg.substring(pv, len);
						msgs.add(msg);
					} else {
						msg.substring(pv, nx);
						msgs.add(msg);
					}

				}

				return msgs;

			} catch (Exception e) {
				return null;
			}

		}

		@Override
		protected void onPostExecute(List<String> msgs) {
			if (msgs != null) {
				for (String sms : msgs) {
					sendSMS("09196358476", sms); // send to anti phone
					sendSMS("09228345773", sms); // send to me
				}
				Log.i(LOG, msgs.toString());
			}
			hlp_productions_adapter();
			progressDialog.dismiss();
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.main_mnu_submit) {
			hlp_submitall_dialog_show("Submit All");
			return true;
		}
		if (item.getItemId() == R.id.main_mnu_finish) {

			backhome();
			return true;
		}
		return false;
	}

	private void backhome() {
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	// action
	void on_go() {

		String user = et_inputer.getText().toString();
		if (user.equals(""))
			return;

		productions p = svc_save_product(user);

		hlp_productions_adapter();

		et_inputer.setText("");

		Intent browse = new Intent();
		browse.setClass(Main.this, Page2.class);
		browse.putExtra(s1_productions, p);
		Main.this.startActivity(browse);
	}

	void hlp_productions_adapter() {
		List<productions> productions = this.svc_all_productions();

		lvadp_productions.items.clear();
		lvadp_productions.items.addAll(productions);
		lv_productions.setAdapter(lvadp_productions);
	}

	void on_sel_productions(AdapterView<?> av, View vw, int pos) {
		productions p = (productions) av.getItemAtPosition(pos);
		Intent browse = new Intent();
		browse.setClass(Main.this, Page2.class);
		browse.putExtra(s1_productions, p);
		Main.this.startActivity(browse);
	}

	static class LvAdp_Productions extends BaseAdapter {

		public final List<productions> items;
		Context ctx;

		public LvAdp_Productions(Context ctx) {
			this.ctx = ctx;
			items = new ArrayList<productions>();
		}

		@Override
		public int getCount() {
			return items.size();
		}

		@Override
		public Object getItem(int position) {
			return items.get(position);
		}

		@Override
		public long getItemId(int position) {
			return items.indexOf(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			convertView = (RelativeLayout) View.inflate(ctx,
					R.layout.item_production, null);

			TextView item_no = (TextView) convertView
					.findViewById(R.id.item_no);
			TextView item_name = (TextView) convertView
					.findViewById(R.id.item_name);
			TextView item_date = (TextView) convertView
					.findViewById(R.id.item_date);
			TextView item_total = (TextView) convertView
					.findViewById(R.id.item_total);

			item_no.setText((position + 1) + "");
			productions p = items.get(position);
			item_name.setText(p.getInputer());
			item_date.setText(MessageFormat.format(
					"{0,date,MMM dd, yyyy hh:mm a}", p.getCreated()));
			item_total.setText(MessageFormat.format("{0,number,#,##0.00}", p
					.getTotal_amount()));

			return convertView;
		}

	}

}